
package com.myopen.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.alibaba.fastjson.JSON;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.myopen.converter.ListConverter;
import com.myopen.kit.UUIDKit;

public class Product extends Model<Product>{

	private static final long serialVersionUID = -6408995522291184390L;
	public static final Product dao=new Product();
	
	public Page<Record> pagequery(Record record){
		StringBuffer sqlExceptSelect=new StringBuffer("from t_shop_product t "
				+ " left join t_shop_category c on t.categoryId=c.id"
				+ " where t.removed='0' ");
		List<Object> list=new ArrayList<Object>();
		
		sqlExceptSelect.append(" order by t.createTime desc");
	
		Page<Record> page= Db.paginate(record.getInt("pageNumber"),record.getInt("pageSize"),"select t.*,c.name categoryName  ",sqlExceptSelect.toString(),list.toArray());		
		String[] dicTypeKeys= {"status"};
		String[] dicTypes= {"SHOP_PRODUCT_STATUS"};
		
		return new ListConverter<Record>(page,dicTypeKeys,dicTypes).getPage();
	}
	
	public Record getPAttr(String attrId){
		Record pAttr=Db.findFirst("select * from t_shop_product_attr t where t.attrId=? ",attrId);
		return pAttr;
	}

	public Record getPAttrValue(String attrValueId){
		Record pAttrValue=Db.findFirst("select * from t_shop_product_attr_value t where t.attrValueId=? ",attrValueId);
		return pAttrValue;
	}

	public List<Record> saveOrupdateSkus(List<Record> skus,String proructId,Record currUser){

		Date now=new Date();

		//保存商品SKU信息
		List<Record> skuAddRecords=new ArrayList<>();
		List<Record> skuUpdateRecords=new ArrayList<>();
		for (Record sku : skus) {

			Record r=null;
			if(StrKit.isBlank(sku.getStr("skuId"))){
				r=new Record();

				List<Record> attrGroup=sku.get("attrGroup");
				List<Record> pAttrGroup=new ArrayList<>();
				for (Record attr : attrGroup) {
					Record rt=new Record();
					String attrId=attr.getStr("attrId");
					String attrValueId=attr.getStr("attrValue");
					//TODO此处效率比较低，前面生命一个Map保存临时的
					Record pAttr=getPAttr(attrId);
					Record pAttrValue=getPAttrValue(attrValueId);

					String pAttrId=pAttr.getStr("id");
					String pAttrValueId=pAttrValue.getStr("id");
					
					rt.set("pAttrId", pAttrId);
					rt.set("pAttrValueId", pAttrValueId);

					pAttrGroup.add(rt);
				}

				r.set("id", UUIDKit.getUUID());
				r.set("removed", "0");
				r.set("createTime", now);
				r.set("updateTime", now);
				r.set("creator", currUser.getStr("id"));
				r.set("updator", currUser.getStr("id"));
				r.set("productId", proructId);
				r.set("pAttrGroup", JsonKit.toJson(pAttrGroup));
				r.set("code", sku.getStr("skuCode"));
				r.set("stock", Integer.parseInt(sku.getStr("skuStock")));
				r.set("price", Double.parseDouble(sku.getStr("skuPrice")));

				skuAddRecords.add(r);
			}else{
				r=Db.findById("t_shop_product_sku", sku.getStr("skuId"));
				r.set("updateTime", now);
				r.set("updator", currUser.getStr("id"));
				r.set("code", sku.getStr("skuCode"));
				r.set("stock", Integer.parseInt(sku.getStr("skuStock")));
				r.set("price", Double.parseDouble(sku.getStr("skuPrice")));

				skuUpdateRecords.add(r);
			}

			
		}
		Db.batchSave("t_shop_product_sku", skuAddRecords, 1000);
		Db.batchUpdate("t_shop_product_sku", skuUpdateRecords, 1000);

		return skus;
	}

	public Record save(Record currUser,Record vo,Record detail,List<Record> attrs,List<Record> skus){
			
		Record bo=new Record();
		if(StrKit.isBlank(vo.getStr("id"))){

			Date now=new Date();

			//保存商品基本信息
			bo.set("id", UUIDKit.getUUID());
			bo.set("createTime", now);
			bo.set("updateTime", now);
			bo.set("creator", currUser.getStr("id"));
			bo.set("updator", currUser.getStr("id"));
			bo.set("status", "0");//下架
			bo.set("categoryId", vo.getStr("categoryId"));
			bo.set("name", vo.getStr("name"));
			bo.set("detail", JsonKit.toJson(detail));

			Db.save("t_shop_product", bo);

			//保存商品属性信息
			List<Record> pAttrList=new ArrayList<>();
			List<Record> pAttrValueList=new ArrayList<>();
			for (Record attr : attrs) {

				String id=UUIDKit.getUUID();
				Record r=new Record();
				r.set("id", id);
				r.set("removed", "0");
				r.set("createTime", now);
				r.set("updateTime", now);
				r.set("creator", currUser.getStr("id"));
				r.set("updator", currUser.getStr("id"));
				r.set("lb", "0");//目前只有一种
				r.set("attrId", attr.getStr("id"));
				r.set("productId", bo.getStr("id"));
				r.set("name",attr.getStr("name"));
				r.set("code",attr.getStr("code"));
				r.set("px",attr.getInt("px"));
				pAttrList.add(r);

				List<Record> attrValues=attr.get("attrValues");
				for (Record attrValue : attrValues) {
					Record rValue=new Record();
					rValue.set("id", UUIDKit.getUUID());
					rValue.set("removed", "0");
					rValue.set("createTime", now);
					rValue.set("updateTime", now);
					rValue.set("creator", currUser.getStr("id"));
					rValue.set("updator", currUser.getStr("id"));
					rValue.set("productId", bo.getStr("id"));
					rValue.set("lb", "0");//目前只有一种
					rValue.set("attrValueId", attrValue.getStr("id"));
					rValue.set("pAttrId", r.getStr("id"));
					rValue.set("value", attrValue.getStr("value"));
					rValue.set("code", attrValue.getStr("code"));
					rValue.set("px",attr.getInt("px"));

					pAttrValueList.add(rValue);
				}

			}
			Db.batchSave("t_shop_product_attr", pAttrList, 1000);
			Db.batchSave("t_shop_product_attr_value", pAttrValueList, 1000);

			//保存商品SKU信息
			saveOrupdateSkus(skus, bo.getStr("id"), currUser);


		}else{

			bo=Db.findById("t_shop_product", vo.getStr("id"));
			//理论上了为了防止商品曾经出现的信息，此处，把修改前的信息要记录到日志里面

			bo.set("updateTime", new Date());
			bo.set("updator", currUser.getStr("id"));
			bo.set("status", "0");//为防止修改完成出现错误，下架该产品，确认无误后，手工上架
			//修改的时候，商品类别不能修改
			bo.set("name", vo.getStr("name"));
			bo.set("detail", JsonKit.toJson(detail));
			Db.update("t_shop_product", bo);

			//修改skus
			//保存商品SKU信息
			saveOrupdateSkus(skus, bo.getStr("id"), currUser);

		}

		return bo;
	}

	public void changeStatus(String id,String status,Record currUser){
		Product bo=Product.dao.findById(id);
		bo.set("updateTime", new Date());
		bo.set("updator", currUser.getStr("id"));
		bo.set("status", status);
		bo.update();
	}

	public List<Record> getPAttrs(String productId){
		String sql="select * from t_shop_product_attr t where t.productId=? order by px";
		List<Record> pAttrs=Db.find(sql,productId);

		if(pAttrs.size()>0){
			StringBuffer sql2=new StringBuffer();
			sql2.append("select * from t_shop_product_attr_value t where pAttrId in (  ");
			List<Object> pAttrIds=new ArrayList<>();
			for (int i = 0; i < pAttrs.size(); i++) {
				pAttrIds.add(pAttrs.get(i).getStr("id"));
				sql2.append(i==0?"?":",?");
			}
			sql2.append(" )");
			sql2.append(" order by px ");
			List<Record> pAttrVs=Db.find(sql2.toString(),pAttrIds.toArray());

			for (Record pAttr : pAttrs) {
				List<Record> pAttrValues=new ArrayList<>();
				for (Record pAttrValue : pAttrVs) {
					if(pAttr.getStr("id").equals(pAttrValue.getStr("pAttrId"))){
						pAttrValues.add(pAttrValue);
					}
				}
				pAttr.set("pAttrValues", pAttrValues);
			}
		}

		return pAttrs;
	}

	@SuppressWarnings("rawtypes")
	public List<Record> getPSkus(String productId){
		String sql="select * from t_shop_product_sku t where t.productId=?";
		List<Record> skus=Db.find(sql,productId);
		for (Record sku : skus) {
			String pAttrGroup=sku.getStr("pAttrGroup");
			List<Map> pAttrGroups=JSON.parseArray(pAttrGroup, Map.class);
			sku.set("pAttrGroups", pAttrGroups);
		}
		return skus;
	}

	@SuppressWarnings("unchecked") 
	public Record getRecordById(String id){
		String sql="select * from t_shop_product t where t.id=? ";
		Record bo=Db.findFirst(sql,id);

		String detailJson=bo.getStr("detail");
		Map<String,Object> detail=(Map<String,Object>)JSON.parse(detailJson);
		List<Record> pAttrs=getPAttrs(bo.getStr("id"));
		List<Record> pSkus=getPSkus(bo.getStr("id"));

		bo.set("detailObj", detail);
		bo.set("pAttrs", pAttrs);
		bo.set("pSkus", pSkus);

		return bo;
	}

	/////////////

	public void formatProductForApi(Record product){
		Map detailObj=new HashMap<>();
		if(StrKit.notBlank(product.getStr("detail"))){
			detailObj=(Map)JSON.parse(product.getStr("detail"));
			List<Map> ext_img=(List<Map>)detailObj.get("ext_img");
			if(ext_img!=null&&ext_img.size()>0){
				product.set("thumbnail", ext_img.get(0));
			}
		}
		product.set("detailObj", detailObj);
	}

	public void formatProductAttrForApi(Record product_attr,List<Record> product_attr_value_all_s){
		List<Record> product_attr_value_s=new ArrayList<>();
		for (Record product_attr_value : product_attr_value_all_s) {
			if(product_attr.getStr("id").equals(product_attr_value.getStr("pAttrId"))){
				product_attr_value_s.add(product_attr_value);
			}
		}
		product_attr.set("product_attr_value_s", product_attr_value_s);
	}

	public void formatProductSkuForApi(Record product_sku){
		List<Map> pAttrGroupObj=new ArrayList<>();
		if(StrKit.notBlank(product_sku.getStr("pAttrGroup"))){
			pAttrGroupObj=JSON.parseArray(product_sku.getStr("pAttrGroup"), Map.class);
		}
		product_sku.set("pAttrGroupObj", pAttrGroupObj);
	}

	public Page<Record> pagequeryForAPI(Record record){
		StringBuffer sqlExceptSelect=new StringBuffer("from t_shop_product t "
				+ " left join t_shop_category c on t.categoryId=c.id"
				+ " where t.removed='0' ");
		List<Object> list=new ArrayList<Object>();
		
		if("search_all".equals(record.getStr("productCategoryId"))){
			//查询全部
		}else{
			sqlExceptSelect.append(" and c.id = ? ");
			list.add(record.getStr("productCategoryId"));
		}

		sqlExceptSelect.append(" order by t.createTime desc");
	
		Page<Record> page= Db.paginate(record.getInt("pageNumber"),record.getInt("pageSize"),"select t.*,c.name categoryName  ",sqlExceptSelect.toString(),list.toArray());		
		String[] dicTypeKeys= {"status"};
		String[] dicTypes= {"SHOP_PRODUCT_STATUS"};
		
		List<Record> ls=page.getList();
		for (Record product : ls) {
			formatProductForApi(product);
		}

		ls=new ListConverter<Record>(ls,dicTypeKeys,dicTypes).getList();
		return new Page<>(ls, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow());
	}

	public List<Record> getRecommendedForAPI(Record record){
		StringBuffer sqlExceptSelect=new StringBuffer("select t.*,c.name categoryName from t_shop_product t "
				+ " left join t_shop_category c on t.categoryId=c.id"
				+ " where t.removed='0' order by t.createTime desc ");
		List<Object> list=new ArrayList<Object>();
	
		List<Record> ls=Db.find(sqlExceptSelect.toString(),list.toArray());
		String[] dicTypeKeys= {"status"};
		String[] dicTypes= {"SHOP_PRODUCT_STATUS"};
		
		for (Record product : ls) {
			formatProductForApi(product);
		}
		

		return new ListConverter<Record>(ls,dicTypeKeys,dicTypes).getList();
	}

	public Record getRecordForAPI(String productId){
		
		Record detail=new Record();
		
		String product_sql="select * from t_shop_product t where t.id=? ";
		Record product=Db.findFirst(product_sql,productId);

		String product_attr_sql="select * from t_shop_product_attr t where t.productId=?  ";
		String product_attr_value_sql="select * from t_shop_product_attr_value t where t.productId=?  ";
		List<Record> product_attr_s=Db.find(product_attr_sql,productId);
		List<Record> product_attr_value_all_s=Db.find(product_attr_value_sql,productId);

		formatProductForApi(product);

		for (Record product_attr : product_attr_s) {
			formatProductAttrForApi(product_attr,product_attr_value_all_s);
		}

		String product_sku_sql="select * from t_shop_product_sku t where t.productId=? ";
		List<Record> product_sku_s=Db.find(product_sku_sql,productId);
		for (Record product_sku : product_sku_s) {
			formatProductSkuForApi(product_sku);
		}

		detail.set("product",product);
		detail.set("product_attr_s",product_attr_s);
		detail.set("product_sku_s",product_sku_s);

		return detail;

	}
    

}
